<template lang="pug">
  div.page-settings
    table.table.settings-table
      caption 基本信息设置
      tbody
        tr
          td 头像
          td
            img.logo.img-responsive(:src='group.logo', v-if='group.logo')
            Avatar(icon='android-person', size='large', v-if='!group.logo')
          td.text-right
            a(@click='modal.logo = true') [修改]
        tr
          td 账号类型
          //- td {{ group.type === 'person' ? '个人号' : '机构号' }}
          td {{ group.type_label }}
          td.text-right
            div(v-if='groupTypeDesc')
              p {{ groupTypeDesc }}
              router-link(to='/upgrade') 续费
            router-link(v-if='!groupTypeDesc', to='/upgrade') 升级至收费版
            //- a(@click='showLogoModal = true') [修改]
        tr
          td 应用账号
          td {{ group.alias }}
          td.text-right
            p 应用访问地址为 {{ protocol }}{{ group.alias }}{{ hostname }}
            a(@click='modal.alias = true') [修改]
        tr
          td 名称
          td {{ group.name }}
          td.text-right
            a(@click='modal.name = true') [修改]
        tr
          td 简介
          td {{ group.intro }}
          td.text-right
            p 请输入应用简介，不得包含违法内容
            a(@click='modal.intro = true') [修改]
        tr
          td 背景图
          td
            img.bg-pic(:src='group.background', v-if='group.background')
          td.text-right
            a(@click='modal.background = true') [修改]
    //- Form(:model='formItem', :label-width='80')
      Row
        Col(:span=2)
          div
            img.logo(:src='logoPreviewUrl()')
            div
              a(@click='showLogoModal = true') [修改]
        Col(:span='10')
          FormItem(label='名称')
            Input(v-model='formItem.label')
          FormItem(label='简介')
            Input(type='textarea', :rows=3, :maxlength=80, v-model='formItem.intro')
            span(style='float: right') {{ formItem.intro.length }}/80
            p 请输入应用简介，不得包含违法内容
          FormItem(label='背景')
            img.bg-pic(:src='bgPreviewUrl()')
            p
             a(@click='showBgModal = true') [修改]
          FormItem
            Button(type='primary', :loading='loading', @click='submit') {{ loading ? '提交中' : '提交' }}
            Button(type='ghost', style='margin-left: 10px') 取消

    Modal.setting-modal(
      title='更改名称'
      v-model='modal.name',
      :loading='true'
      @on-ok='updateName'
      @on-cancel='formItem.name = group.name'
    )
      Input(v-model='formItem.name')

    Modal.setting-modal(
      title='更改别名'
      v-model='modal.alias',
      :loading='true'
      @on-ok='updateAlias'
      @on-cancel='formItem.alias = group.alias'
    )
      p 输入4-16个字符，只允许输入数字、字母
      Input(v-model='formItem.alias', :maxlength=16, style='width: 220px; text-align: right;')
        span(slot='prepend') {{ protocol }}
        span(slot='append') {{ hostname }}

    Modal.setting-modal.setting-modal__intro(
      title='编辑简介'
      v-model='modal.intro',
      width=600,
      :loading='true'
      @on-ok='updateIntro'
      @on-cancel='formItem.intro = group.intro'
    )
      p 请输入应用简介，不得包含违法内容
      Input(type='textarea', :rows=3, :maxlength=80, v-model='formItem.intro')
      span(style='float: right') {{ formItem.intro.length }}/80

    Modal.setting-modal(
      title='编辑LOGO'
      v-model='modal.logo',
      :width=600,
      :loading='true'
      @on-ok='upload("logo")',
      @on-cancel='resetUpload')
      div
        p.hint(style='margin-bottom: 8px') 新头像不允许涉及政治敏感与色情; 图片格式必须为：png,bmp,jpeg,jpg,gif；不可大于2M；建议使用png格式图片，以保持最佳效果；建议图片尺寸为144px*144px
        Upload(ref='upload',
          action='javascript:;',
          :show-upload-list='false',
          :before-upload='beforeUpload')
          Button(type='ghost', icon='ios-cloud-upload-outline') 选择图片
          //- div(item in uploadList)
          //- Progress(v-if="uploadItem.showProgress", :percent="uploadItem.percentage", hide-info)
        div
          p 预览
          img(:src='logoPreviewUrl()', style='width: 144px; height: 144px; border-radius: 6px;')
          img(:src='logoPreviewUrl()', style='width: 144px; height: 144px; margin-left: 16px; border-radius: 50%;')

    Modal.setting-modal(
      title='编辑背景',
      v-model='modal.background',
      :width=800,
      :loading='true',
      @on-ok='upload("background")',
      @on-cancel='resetUpload'
      )
      //- div(slot='header') 编辑背景
      div
        div 自定义
          div
            a(:href='bgPreviewUrl()', target='_blank')
              img(:src='bgPreviewUrl()', style='width: 320px;')
            Upload(ref='upload',
              action='javascript:;',
              :show-upload-list='false',
              :before-upload='beforeUpload')
              Button(type='ghost', size='small', icon='ios-cloud-upload-outline') {{ formItem.background ? '替换图片' : '上传图片' }}
              //- div(item in uploadList)
        //- div 预设
          Row(type='flex')
            Col(:span=6)
              a(href='//placehold.it/120x75', target='_blank')
                img(src='//placehold.it/120x75')
            Col(:span=6)
              a(href='//placehold.it/120x75', target='_blank')
                img(src='//placehold.it/120x75')
            Col(:span=6)
              a(href='//placehold.it/120x75', target='_blank')
                img(src='//placehold.it/120x75')
            Col(:span=6)
              a(href='//placehold.it/120x75', target='_blank')
                img(src='//placehold.it/120x75')

</template>

<script>
import { mapState } from 'vuex'
import Api from '@/apis/group'
import fileApi from '@/apis/file'
import store from '@/store'

export default {
  name: 'settings',
  data () {
    return {
      loading: false,
      modal: {
        name: false,
        alias: false,
        intro: false,
        logo: false,
        background: false
      },
      uploadItem: {},
      group: {},
      formItem: {
        logo: null,
        label: '',
        alias: '',
        intro: '',
        background: null
      },
      file: null,
      preview: {}
    }
  },
  computed: {
    protocol () {
      return location.protocol + '//'
    },
    hostname () {
      // return '.' + location.hostname.match(/(console\.)?(.*)/)[2]
      return '.qybee.com'
    },
    groupTypeDesc () {
      if (this.group.subscription && 'expire' in this.group.subscription) {
        return '到期时间: ' + this.group.subscription.expire
      }
    },
    ...mapState({
      appId: state => state.app.id
    })
  },
  beforeRouteEnter (to, from, next) {
    // next()
    // console.log(store.state.app.id)
    // next()
    Api.getGroup(store.state.app.id).then(data => {
      // console.log(data.data)
      next(vm => {
        vm.group = data
        vm.formItem.name = data.name
        vm.formItem.alias = data.alias
        vm.formItem.intro = data.intro
        vm.formItem.logo = data.logo
        vm.formItem.background = data.background
      })
    })
  },
  methods: {
    beforeUpload (file) {
      // console.log('before upload', file)
      this.file = file

      let reader = new FileReader()
      reader.onload = e => {
        this.uploadPreview = e.target.result
        this.$forceUpdate()
      }
      reader.readAsDataURL(file)

      return false
    },
    submit () {
      this.loading = true
      const pack = {
        id: this.appId,
        name: this.formItem.name,
        intro: this.formItem.intro
      }
      Api.patchGroup(pack)
        .then(data => {
          this.loading = false

          this.group = data
          this.formItem.name = data.name
          this.formItem.intro = data.intro
          this.formItem.logo = data.logo
          this.formItem.background = data.background

          this.$Message.success('保存成功')
        })
    },
    async updateName () {
      const pack = {
        id: this.appId,
        name: this.formItem.name
      }
      Api.patchGroup(pack)
        .then(data => {
          this.group = data
          this.formItem.name = data.name

          this.modal.name = false
        })
    },
    async updateAlias () {
      const pack = {
        id: this.appId,
        alias: this.formItem.alias
      }
      Api.patchGroup(pack)
        .then(data => {
          this.group = data
          this.formItem.alias = data.alias

          this.modal.alias = false
        })
    },
    async updateIntro () {
      const pack = {
        id: this.appId,
        intro: this.formItem.intro
      }
      Api.patchGroup(pack)
        .then(data => {
          this.group = data
          this.formItem.intro = data.intro

          this.modal.intro = false
        })
    },
    async upload (field) {
      let uri = this.uploadPreview.replace(`data:${this.file.type};base64,`, '')
      let data = {
        filename: [{ value: this.file.name }],
        data: [{ value: uri }]
      }
      try {
        const res = await fileApi.uploadImage(data)
        if (res.status === 201 && res.data.fid[0].value) {
          // return res.data.fid[0].value
          const group = await Api.patchGroup({ id: this.appId, [field]: res.data.fid[0].value })
          this.modal[field] = false
          this.group = group
          this.resetUpload()
        }
      } catch (e) {}
    },
    resetUpload () {
      this.uploadPreview = null
      this.file = null
    },
    logoPreviewUrl () {
      return this.uploadPreview || this.group.logo || 'http://placehold.it/144x144'
    },
    bgPreviewUrl () {
      return this.uploadPreview || this.group.background || 'http://placehold.it/120x75'
    }
  }
}
</script>


<style scoped>
.logo {
  max-width: 114px;
  height: auto;
}
</style>

<style lang="less">

.bg-pic {
  max-width: 100%;
  height: auto;
}

.setting-modal .ivu-modal-body {
  padding: 40px;
}

.page-settings .table {
  font-size: 14px;

  caption {
    padding: 12px 16px !important;
  }
  td {
    padding: 16px !important;
    vertical-align: top;

    &:first-child {
      width: 80px;
      color: #999;
      // font-size: 14px;
    }

    &:nth-child(3) {
      width: 40%;
      color: #999;
    }
  }
}

.setting-modal__intro {
  color: #999;
  p {
    font-size: 14px;
    margin-bottom: 8px;
  }
  span {
    margin-top: 5px;
  }
}
</style>
